package com.gin.kotlin.no_gay_alliance.provider.ngajs

import android.annotation.SuppressLint
import android.content.Context
import android.webkit.JavascriptInterface
import android.webkit.WebView
import com.gin.kotlin.no_gay_alliance.base.AlertDialogUtils
import com.gin.kotlin.no_gay_alliance.base.MyHandler
import com.gin.kotlin.no_gay_alliance.callback.SCallback
import com.gin.kotlin.no_gay_alliance.enums.HandlerMessageWhat.POST_ADD_TEXT_TO_CONTENT
import com.gin.kotlin.no_gay_alliance.model.PostAddTextModel
import com.gin.nga.api.ResourceApi
import com.gin.nga.response.resource.bbscode.BbsCodeBody
import java.lang.ref.WeakReference

class ColorProvider private constructor(): AbstractNgaResourceProvider<BbsCodeBody, List<String>>(
    javaType = TYPE_FACTORY.constructCollectionLikeType(List::class.java, String::class.java),
) {
    override val relativePath = "$DIR/colors.json"


    override fun requestMethod(resourceApi: ResourceApi) = resourceApi.bbsCode()

    override fun transform(res: BbsCodeBody?) = res?.fontColor

    companion object {
        private var instance: WeakReference<ColorProvider> = WeakReference(ColorProvider())
        fun getInstance(): ColorProvider = instance.get() ?: ColorProvider().also { instance = WeakReference(it) }

        fun showColorSelector(context: Context,handler: MyHandler?=null){
            val selector = context.assets.open("color_selector.html").bufferedReader().readText()
            val colorSpan = context.assets.open("color_span.html").bufferedReader().readText()
            getInstance().enqueue(callback = object : SCallback<List<String>> {
                @SuppressLint("SetJavaScriptEnabled")
                override fun onSuccess(data: List<String>) {
                    // 色块
                    val spans = data.joinToString("") { colorSpan.replace("[颜色占位]", it) }
                    // 完整HTML
                    val html = selector.replace("[正文占位]", spans)

                    val webView = WebView(context).also {
                        it.settings.javaScriptEnabled = true
                    }
                    // 加载html代码
                    webView.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null)


                    val dialog = AlertDialogUtils.builder(context, "选择颜色", contentView = webView).show()

                    // 点击响应
                    webView.addJavascriptInterface(object :Any(){
                        @JavascriptInterface
                        fun chooseColor(color:String){
                            handler?.sendMessage(POST_ADD_TEXT_TO_CONTENT, PostAddTextModel("[color=${color}]", "[/color]"))
                            dialog.hide()
                        }
                    },"android")
                }

                override fun onFailure(call: okhttp3.Call, e: java.io.IOException) {
                    e.printStackTrace()
                }
            })
        }
    }
}